package com.lanou.weekend02.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lizhongren1.
 */
@Aspect
@Component
public class CustomAspect {

    private static final Logger LOG = LoggerFactory.getLogger(CustomAspect.class);

    @Pointcut("execution(public * com.lanou.weekend02.controller..*.*(..))")
    public void pc(){}

    /**
     * @param joinPoint
     */
    @Before("pc()")
    public void beforeMethod(JoinPoint joinPoint) throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求相关参数
        LOG.info("========================================== 请求开始 ==========================================");
        // 打印请求 url
        LOG.info("请求地址是       : {}", request.getRequestURL().toString());
        // 打印 Http method
        LOG.info("HTTP请求方法     : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
//        LOG.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        LOG.info("IP地址          : {}", request.getRemoteAddr());
        // 打印请求入参
        LOG.info("请求参数列表     : {}", joinPoint.getArgs());

    }

    /**
     * 在切点之后织入
     * @throws Throwable
     */
    @After("pc()")
    public void doAfter() throws Throwable {
        LOG.info("=========================================== 请求结束 ===========================================");
        // 每个请求之间空一行
        LOG.info("");
    }



}
